package com.pzl.util;

import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;

import com.orhanobut.logger.Logger;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by zl.peng on 2017/6/12 13:19.
 */

public class ImageUtil {

    /**
     * 将图片保存到指定文件夹中
     *
     * @param filePath
     * @param bitmap
     * @param quality
     * @return
     */
    public static boolean saveFilePicture(String filePath, Bitmap bitmap, int quality) {
        String imageFormat = filePath.substring(filePath.lastIndexOf("."));
        File f = null;
        FileOutputStream fos = null;
        try {
            f = new File(filePath);
            // 创建新文件
            if (!f.exists()) {
                f.createNewFile();
            }
            fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            // 保存图片格式
            if (imageFormat.equals(".jpg") || imageFormat.equals(".JPG")) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            } else if (imageFormat.equals(".png") || imageFormat.equals(".PNG")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos);
            } else {
                Logger.d("图片格式不正确，只为.jpg, .png格式！");
                return false;
            }
            return true;
        } catch (FileNotFoundException e) {
            Logger.e("保存失败，文件没发现", e);
        } catch (IOException e) {
            Logger.e("保存失败，操作流文件错误", e);
        } catch (NullPointerException e) {
            Logger.e("保存失败，文件没发现", e);
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e("保存失败，关闭流错误", e);
            }
        }
        return false;
    }

    /**
     * 将图片保存到指定文件夹images_temp中
     *
     * @param fileName 图片名称
     * @param bitmap   图片
     */
    public static void saveFileImage(String fPath, String fileName, Bitmap bitmap) {
        String imageFormat = fileName.substring(fileName.lastIndexOf("."));
        String filePath = createSDCardFolder(fPath) + File.separator + fileName;
        File f = null;
        try {
            f = new File(filePath);
            f.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 保存图片格式
        if (imageFormat.equals(".jpg") || imageFormat.equals(".JPG")) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } else if (imageFormat.equals(".png") || imageFormat.equals(".PNG")) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } else {
            Logger.d("图片格式不正确，只为.jpg, .png格式！");
        }
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文件夹
     *
     * @return 返回文件夹路径
     */
    public static String createSDCardFolder(String dirFolder) {
        String extSdCard = getSDPath();
        if (TextUtils.isEmpty(extSdCard)) {
            extSdCard = getExtSDCard();
        }
        File folder = new File(extSdCard + File.separator + dirFolder);
        if (folder.exists() == false) {
            folder.mkdirs(); // 创建文件夹完整路径
        }
        return folder.toString();
    }

    /**
     * 判断sdcard是否存在，并返回sdcard路径。
     *
     * @return 返回sdcard路径
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (sdDir == null) {
            return null;
        }
        return sdDir.toString();
    }


    public static String getExtSDCard() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            String mount = new String();
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;

                if (line.contains("fat")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        mount = mount.concat(columns[1]);
                    }
                } /*
                 * else if (line.contains("fuse")) { String columns[] =
				 * line.split(" "); if (columns != null && columns.length > 1) {
				 * mount = mount.concat(columns[1] + "\n"); } }
				 */
            }
            return mount;
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage(), e);
        } catch (IOException e) {
            Logger.e(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 拼接拍照后的图片路劲，分号";" 隔开
     *
     * @param filePathList
     * @return
     */
    public static String joinFilesListToString(List<String> filePathList) {
        String filesPath = "";
        if (filePathList != null && filePathList.size() > 0) {
            for (String str : filePathList) {
                if (!filesPath.equals("")) {
                    filesPath += ";" + str;
                } else {
                    filesPath = str;
                }
            }
        }
        return filesPath;
    }

}
